import {createRouter,createWebHistory} from 'vue-router'
import {ElMessageBox} from 'element-plus'
import {addRouters} from '../util/syncRouter'


const router =  createRouter({
    history:createWebHistory(),
    routes:[
        {
            name:'login',
            path:'/',
            component:()=>import('@/views/Login/Login.vue')
        },
        {
            name:'admin',
            path:'/admin',
            component:()=>import('@/views/Admin/Admin.vue')
        },
    ]
})

let registerRouterFresh = true;
router.beforeEach((to,from,next)=>{
    if(to.path != '/'){
        //判断是否有token
        if(window.sessionStorage.getItem('token') == 'undefined' || window.sessionStorage.getItem('token') == '' || window.sessionStorage.getItem('token') == null){
            ElMessageBox.alert('你还没有登录，请先登录','警告',{
                confirmButtonText:'好的',
                type: 'error',
                draggable: true,
            }).then(()=>{
                next('/');
            })
        }else{
            //判断是不是本页面刷新的，如果是本页面刷新的，就需要重新添加上路由
            if(!from.name && registerRouterFresh){
                addRouters();
                next({...to,replace:true});
                registerRouterFresh = false;   //加上这个判断，要不然程序走到next({...to,replace:true})之后一直递归，就会一直循环。。。跳不出
            }else{
                next();
            }
        }
    }else{
        next();
    }
})
export default router;